package com.xxl.sso.server.controller;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.xxl.sso.core.entity.ReturnT;
import com.xxl.sso.core.util.RandomValidateCodeUtil;
import com.xxl.sso.server.controller.req.vo.EmailRequest;
import com.xxl.sso.server.core.base.BaseWebController;
import com.xxl.sso.server.service.EmailCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/captcha")
public class EmailCaptchaController extends BaseWebController {

    @Autowired
    private CaptchaService captchaService;


    /**
     * 跳转到登陆页面页面
     */
    private static final String MB_LOGIN_FTL = "loginByEmail";

    @Autowired
    private EmailCaptchaService emailCaptchaService;

    @PostMapping("/email/send")
//    public ResponseEntity<?> sendEmailCaptcha(String email, Model model) {
    public ResponseEntity<?> sendEmailCaptcha(@RequestBody EmailRequest request, Model model, HttpSession httpSession) {
//    public ResponseEntity<?> sendEmailCaptcha(Model model) {
        System.out.println("执行sendemail");

        String email = request.getEmail();

        // 1.图形验证码判断
        //之后改成滑动验证码
//        if (!RandomValidateCodeUtil.checkVerify(graphicCode, httpSession)) {
//            setErrorMsg(model, "图形验证码不正确!");
//            return ResponseEntity.badRequest().body(MB_LOGIN_FTL);
////            return MB_LOGIN_FTL;
//        }
        // 发送邮箱验证码
        boolean sent = emailCaptchaService.sendEmailCaptcha(email);

        if (sent) {
            setErrorMsg(model, "验证码已发送，请查收邮件!1");
            return ResponseEntity.ok(new ReturnT(200, "验证码已发送，请查收邮件!2"));
        } else {
//            setErrorMsg(model, "验证码发送失败，请稍后再试");
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body(new ApiResponse(false, "验证码发送失败，请稍后再试"));
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 验证邮箱格式
    private boolean isValidEmail(String email) {
//        String regex = "^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$";
        String regex = "\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
        return email != null && email.matches(regex);
    }
}
